package com.slipper.system.affix.controller;

import com.slipper.common.bo.Result;
import com.slipper.common.permit.PermitAll;
import com.slipper.common.util.*;
import com.slipper.system.affix.common.AffixInfo;
import com.slipper.system.api.affix.bo.AffixItemBO;
import com.slipper.system.api.affix.service.IAffixItemSv;
import com.slipper.system.common.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/affix")
public class AffixController {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${file.save.mode}")
    private String fileSaveMode;
    @Value("${file.save.path}")
    private String fileSavePath;

    @Resource
    private IAffixItemSv affixItemSv;

    @PermitAll
    @PostMapping(value = "/queryItems")
    public String queryItems(@RequestBody AffixItemBO bo) {
        return ResultUtil.toJson(this.affixItemSv.queryList(bo));
    }

    @PermitAll
    @PostMapping(value = "/deleteItem")
    public String deleteItem(@RequestBody AffixItemBO bo) {
        Result<AffixItemBO> result = this.affixItemSv.queryBy(bo.getId());
        if (result.isSuccess() && result.getData() != null) {
            return ResultUtil.toJson(this.affixItemSv.delete(bo.getId()));
        } else {
            return ResultUtil.toErrorJson("文件不存在!");
        }
    }

    /**
     * 附件上传
     */
    @PermitAll
    @PostMapping(value = "/upload")
    public String upload(AffixInfo info) throws IOException {
        AffixItemBO affixItem = new AffixItemBO();
        this.uploadFileData(affixItem, info);
        affixItem.setCreateId(Constants.getCurrentUser().getEmployeeId());
        affixItem.setCreateTime(new Date());
        return ResultUtil.toJson(this.affixItemSv.save(affixItem));
    }

    /**
     * 文件下载
     */
    @PermitAll
    @PostMapping("/download")
    public void download(HttpServletResponse response, @RequestBody AffixItemBO bo) {
        if (bo.getId() == null || "".equals(bo.getId())) {
            return;
        }
        Result<AffixItemBO> result = this.affixItemSv.queryBy(bo.getId());
        if (result.isSuccess() && result.getData() == null) {
            this.logger.error("附件不存在: {}", bo.getId());
            return;

        }

        FileUtil.downloadFile(
                response,
                result.getData().getTrueName(),
                result.getData().getSavePath());
    }

    /**
     * 打包下载
     */
    @PermitAll
    @PostMapping("/downloadAll")
    public void downloadAll(HttpServletResponse response, @RequestBody AffixItemBO bo) throws Exception {
        Result<List<AffixItemBO>> result = this.affixItemSv.queryList(bo);
        if (result.isSuccess() && !result.getData().isEmpty()) {
            if (result.getData().size() == 1) {
                AffixItemBO affixItem = result.getData().get(0);
                FileUtil.downloadFile(
                        response,
                        affixItem.getTrueName(),
                        affixItem.getSavePath());
            } else {
                List<String> fileIdList = new ArrayList<>();
                List<String> fileNameList = new ArrayList<>();
                for (AffixItemBO affixItem : result.getData()) {
                    fileNameList.add(affixItem.getTrueName());
                    fileIdList.add(affixItem.getSavePath());
                }

                String fileName = "附件打包" + DateUtil.format(new Date(), "yyyyMMdd")+ ".zip";
                FileUtil.downloadZip(response, fileName, fileNameList, fileIdList);
            }
        }
    }

    /**
     * 上传文件并获取AffixItem数据
     * @param affixItem 接收获得的数据
     * @param info 上传文件表单
     */
    private void uploadFileData(AffixItemBO affixItem, AffixInfo info) throws IOException {
        String savePath = FileUtil.getFilePath(this.fileSavePath, this.fileSaveMode);
        File savePathFile = new File(savePath);
        if (!savePathFile.isFile()) {
            savePathFile.mkdirs();
        }

        if (info.getFile() != null) {
            MultipartFile multipartFile = info.getFile();
            String trueName = multipartFile.getOriginalFilename();
            String fileExtension = FileUtil.getExtension(trueName);
            if (!fileExtension.isEmpty()) {
                affixItem.setSaveName(FileUtil.getFileName() + "." + fileExtension);
            } else {
                affixItem.setSaveName(FileUtil.getFileName());
            }
            affixItem.setFileSize(new Long(multipartFile.getSize()).intValue());
            affixItem.setTrueName(trueName);
            affixItem.setAffixId(info.getAffixId());
            affixItem.setSavePath(savePath + affixItem.getSaveName());
            multipartFile.transferTo(new File(savePathFile, affixItem.getSaveName()));
        }
    }

    /**
     * 获取附件列表
     */
    @PermitAll
    @PostMapping(value = "/queryList")
    public String queryList(@RequestBody AffixItemBO bo){
        return ResultUtil.toJson(this.affixItemSv.queryList(bo));
    }

    /**
     * 图片下载
     */
    @PermitAll
    @GetMapping("/image/{id}")
    public void showImage(HttpServletResponse response, @PathVariable("id") String id) {
        if (id == null || id.isEmpty()) {
            return;
        }
        Result<AffixItemBO> result = this.affixItemSv.queryBy(id);
        AffixItemBO affixItem;
        if (result.getData() == null) {
            affixItem = this.affixItemSv.queryByAffixId(id).getData();
        } else {
            affixItem = result.getData();
        }
        if (result.getData() == null && affixItem == null) {
            this.logger.error("附件不存在: {}", id);
            return;
        }

        FileUtil.downloadFile(response, affixItem.getTrueName(), affixItem.getSavePath());
    }
}
